/*
 *    Copyright 2022 jacky4631 shen ji email:121659050@qq.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dataoke.shoppingguide.app773026.activity.home.fragment.category;


import static com.dataoke.shoppingguide.app773026.bean.Constants.DA_TAO_KE_GET_CATEGORY_URL;

import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.dataoke.shoppingguide.app773026.R;
import com.dataoke.shoppingguide.app773026.activity.home.fragment.category.adapter.DetailRecycleAdapter;
import com.dataoke.shoppingguide.app773026.activity.home.fragment.category.adapter.LeftRecycleAdapter;
import com.dataoke.shoppingguide.app773026.activity.home.fragment.category.adapter.RightRecycleAdapter;
import com.dataoke.shoppingguide.app773026.activity.search.SearchActivity;
import com.dataoke.shoppingguide.app773026.activity.subcategory.CategoryActivity;
import com.dataoke.shoppingguide.app773026.base.fragments.BaseFragment;
import com.dataoke.shoppingguide.app773026.bean.DataokeGetCategoryDataBean;
import com.dataoke.shoppingguide.app773026.bean.DataokeGetCategoryResBean;
import com.dataoke.shoppingguide.app773026.bean.DataokeGetCategorySubDataBean;
import com.dataoke.shoppingguide.app773026.util.GlideUtils;
import com.dataoke.shoppingguide.app773026.util.HttpTools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 分类界面
 * @author: shen ji
 * @date: 2022/3/15
 * @email: 121659050@qq.com
 * @wechat: jacky4631
 */
public class CategoryFragment extends BaseFragment implements
        View.OnClickListener {
    RecyclerView leftRecycle;
    RecyclerView rightRecycle;

    LeftRecycleAdapter leftAdapter;
    RightRecycleAdapter rightAdapter;


    List<DataokeGetCategoryDataBean> leftList = new ArrayList<>();

    List<DataokeGetCategoryDataBean> rightList = new ArrayList<>();

    int currentPosition = 0;

    public static CategoryFragment newInstance() {
        return new CategoryFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_category;
    }

    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        leftRecycle = root.findViewById(R.id.main_left_recycle);
        rightRecycle = root.findViewById(R.id.main_right_recycle);
        leftRecycle.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rightRecycle.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

        leftAdapter = new LeftRecycleAdapter(getContext(), R.layout.item_main_left, leftList);
        leftRecycle.setAdapter(leftAdapter);

        rightAdapter = new RightRecycleAdapter(getContext(), R.layout.item_main_right, rightList);
        rightRecycle.setAdapter(rightAdapter);


        leftAdapter.setCallBack((holder, bean, position) -> {
            LinearLayout layout = (LinearLayout) holder.getView(R.id.item_main_left_layout);
            TextView type = (TextView) holder.getView(R.id.item_main_left_type);
            type.setText(bean.getCname().substring(0, 2));
            if (position == currentPosition) {
                layout.setBackgroundColor(0xffffffff);
                type.setTextColor(getResources().getColor(R.color.price));
            } else {
                layout.setBackgroundColor(0xffeeeeee);
                type.setTextColor(0xff444444);
            }
            ImageView imageView = (ImageView) holder.getView(R.id.item_main_left_img);
            GlideUtils.loadCategoryImg(getContext(), bean.getCpic(), imageView);
        });

        leftAdapter.setOnItemClickListner((v, position) -> {
            Log.i("leftAdapter", "scrollToPositionWithOffset-->" + position);
            LinearLayoutManager llm = ((LinearLayoutManager) rightRecycle.getLayoutManager());
            llm.scrollToPositionWithOffset(position, 0);

        });


        rightAdapter.setCallBack((holder, bean, position) -> {
            holder.setText(R.id.item_main_right_type, bean.getCname());
            RecyclerView detailsRecycle = (RecyclerView) holder.getView(R.id.item_main_right_recycle);
            updateDetailsRecycle(detailsRecycle, bean);
        });

        rightRecycle.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            LinearLayoutManager rightManager = (LinearLayoutManager) rightRecycle.getLayoutManager();

            LinearLayoutManager leftManager = ((LinearLayoutManager) leftRecycle.getLayoutManager());

            /**
             * 获取第一个item为第几个position
             */
            currentPosition = rightManager.findFirstVisibleItemPosition();


            /**
             * 这地方需要进行判断，如果右边的Recycle在移动的时候，左边的RecycleView也是需要进行移动的
             * 左边的recycleview有可能会不可见，这时候，我们必须去判断一下，左边最后的一个item是不是
             * 小于右边滑动的位置，或左边第一个item是不是大于右边滑动的位置
             */
            if (leftManager.findFirstVisibleItemPosition() > currentPosition) {
                leftManager.scrollToPositionWithOffset(currentPosition, 0);
            } else if (leftManager.findLastVisibleItemPosition() < currentPosition) {
                leftManager.scrollToPositionWithOffset(currentPosition, 0);
            }

            /**
             * 判断右边是否滑动到最后一个item，是的话，也将左边移动到最后一个item
             * canScrollVertically(1)表示是否能向上滚动，false表示已经滚动到底部
             */
            if (!rightRecycle.canScrollVertically(1)) {
                currentPosition = rightList.size() - 1;

                Log.i("tag", currentPosition + "-------");
            }


            leftAdapter.notifyDataSetChanged();
        });
    }

    /**
     * 更新详情列表
     *
     * @param detailsRecycle
     */
    public void updateDetailsRecycle(RecyclerView detailsRecycle, DataokeGetCategoryDataBean bean) {
//        detailsList.addAll(bean.getSubcategories());
        DetailRecycleAdapter detailsAdapter = new DetailRecycleAdapter(getContext(), R.layout.item_main_details, bean.getSubcategories());
        detailsAdapter.setCallBack((holder, subBean, position) -> {
            TextView type = (TextView) holder.getView(R.id.tv_title);
            type.setText(subBean.getSubcname());
            ImageView imageView = (ImageView) holder.getView(R.id.iv_pic);
            GlideUtils.loadImgCrop(getContext(), subBean.getScpic(), imageView);
        });
        detailsAdapter.setOnItemClickListner((v, position) -> CategoryActivity.show(getContext(), (ArrayList<DataokeGetCategorySubDataBean>) bean.getSubcategories(), position));
        detailsRecycle.setLayoutManager(new GridLayoutManager(getContext(), 3));
        detailsRecycle.setAdapter(detailsAdapter);
    }


    /**
     * 初始化数据源
     */
    protected void initData() {
        HttpTools.get(DA_TAO_KE_GET_CATEGORY_URL, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("CategoryFragment", DA_TAO_KE_GET_CATEGORY_URL + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                DataokeGetCategoryResBean resBean = JSON.parseObject(response.body().string(), DataokeGetCategoryResBean.class);
                if(resBean.getCode() == 0) {
                    leftList.addAll(resBean.getData());
                    rightList.addAll(resBean.getData());
                    getActivity().runOnUiThread(() -> {

                        leftAdapter.notifyDataSetChanged();
                        rightAdapter.notifyDataSetChanged();
                    });
                }
            }
        });
    }


    @OnClick({R.id.iv_search})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                SearchActivity.show(getContext());
                break;
        }
    }

}
